package com.k12.admim.service.impl;

import com.k12.admim.model.dto.RegUserDTO;
import com.k12.admim.model.entity.sys.*;
import com.k12.admim.model.vo.sys.*;
import com.k12.admim.rpc.UserFeignClient;
import com.k12.admim.service.OperatorUserService;
import com.k12.admim.utils.RequestContextUtil;
import com.k12.common.model.resp.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("OperatorUserService")
@Log4j2
public class OperatorUserServiceImpl implements OperatorUserService {

    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public List<SysDeptVo> selectDeptTree(SysUserVo sysUserVo) {
        List<SysDeptVo> sysDepts = userFeignClient.getAllDept(sysUserVo);
        return sysDepts;

    }

    @Override
    public R register(RegUserVo regUserVo) {
        try {
            //校验是否存在用户信息
            String message = userFeignClient.checkRegister(regUserVo);
            if ("".equals(message)) {
                Long userId = userFeignClient.addUser(regUserVo);
                if (regUserVo.getPostIds() != null && regUserVo.getPostIds().length > 0) {
                    // 新增用户与岗位管理
                    Long[] posts = regUserVo.getPostIds();
                    List<SysUserPostVo> list = new ArrayList<SysUserPostVo>(posts.length);
                    for (Long postId : posts) {
                        SysUserPostVo up = new SysUserPostVo();
                        up.setUserId(userId);
                        up.setPostId(postId);
                        up.setTenantId(regUserVo.getTenantId());
                        list.add(up);
                    }
                    userFeignClient.addPost(list);
                }

                if (regUserVo.getRoleIds() != null && regUserVo.getRoleIds().length > 0) {
                    // 新增用户与岗位管理
                    Long[] roleIds = regUserVo.getRoleIds();
                    List<SysUserRoleVo> list = new ArrayList<SysUserRoleVo>(roleIds.length);
                    for (Long roleId : roleIds) {
                        SysUserRoleVo ur = new SysUserRoleVo();
                        ur.setUserId(userId);
                        ur.setRoleId(roleId);
                        ur.setTenantId(regUserVo.getTenantId());
                        list.add(ur);
                    }
                    userFeignClient.addUserRole(list);
                }
                log.info("注册成功,userId================{}",userId);
                return R.success();
            } else {
                return R.failed(message);
            }
        } catch (Exception e) {
            log.info("注册失败,具体原因===============：{}",e.getMessage());
            return R.failed("注册失败");
        }
    }

    @Override
    public List<SysUser> checkUser(String tenantId, Long userId) {
        return userFeignClient.selectUserDept(tenantId, userId);
    }

    @Override
    public RegUserDTO getUser(Long userId, String tenantId) {
        RegUserDTO regUserDTO = new RegUserDTO();
        List<Long> roleIds = userFeignClient.getRoleIds(userId, tenantId);
        List<SysRole> allRoles = userFeignClient.getAllRoles(tenantId);
        List<Long> allPostIds = userFeignClient.getAllPostIds(tenantId, userId);
        List<SysPost> allPost = userFeignClient.getPostByTenantId(tenantId);
        regUserDTO.setRoleIds(roleIds);
        regUserDTO.setRoles(allRoles);
        regUserDTO.setPostIds(allPostIds);
        regUserDTO.setPosts(allPost);
        SysUserVo sysUserVo = userFeignClient.selectUserById(tenantId, userId);
        SysDept sysDept = userFeignClient.selectDept(tenantId, userId);
        sysUserVo.setDept(sysDept);
        regUserDTO.setUser(sysUserVo);
        return regUserDTO;
    }

    @Override
    public R updateUser(RegUserVo regUserVo) {
        try {
            //校验是否存在用户信息
            String message = userFeignClient.checkRegister(regUserVo);
            if ("".equals(message)) {

                if (regUserVo.getPostIds() != null && regUserVo.getPostIds().length > 0) {
                    // 新增用户与岗位管理
                    Long[] posts = regUserVo.getPostIds();
                    List<SysUserPostVo> list = new ArrayList<SysUserPostVo>(posts.length);
                    for (Long postId : posts) {
                        SysUserPostVo up = new SysUserPostVo();
                        up.setUserId(regUserVo.getUserId());
                        up.setPostId(postId);
                        up.setTenantId(regUserVo.getTenantId());
                        list.add(up);
                    }
                    userFeignClient.deletePost(regUserVo.getUserId(), regUserVo.getTenantId());
                    userFeignClient.addPost(list);
                }

                if (regUserVo.getRoleIds() != null && regUserVo.getRoleIds().length > 0) {
                    // 新增用户与岗位管理
                    Long[] roleIds = regUserVo.getRoleIds();
                    List<SysUserRoleVo> list = new ArrayList<SysUserRoleVo>(roleIds.length);
                    for (Long roleId : roleIds) {
                        SysUserRoleVo ur = new SysUserRoleVo();
                        ur.setUserId(regUserVo.getUserId());
                        ur.setRoleId(roleId);
                        ur.setTenantId(regUserVo.getTenantId());
                        list.add(ur);
                    }
                    userFeignClient.deleteUserRole(regUserVo.getUserId(), regUserVo.getTenantId());
                    userFeignClient.addUserRole(list);
                }
                userFeignClient.update(regUserVo);
                log.info("注册成功,userId================{}",regUserVo.getUserId());
                return R.success();
            } else {
                return R.failed(message);
            }
        } catch (Exception e) {
            log.info("注册失败,具体原因===============：{}",e.getMessage());
            return R.failed("注册失败");
        }
    }

    @Override
    public void deleteByIds(Long[] userIds, String tenantId) {
        for (Long userId : userIds){
            userFeignClient.deleteUserRole(userId, tenantId);
            userFeignClient.deletePost(userId, tenantId);
            userFeignClient.deleteSysUser(userId, tenantId);
        }
    }

    @Override
    public void resetPwd(RegUserVo regUserVo) {
        userFeignClient.update(regUserVo);
    }

    @Override
    public void insertUserAuth(Long userId, Long[] roleIds,String tenantId) {
        userFeignClient.deleteUserRole(userId,tenantId);
        insertUserRole(userId,roleIds,tenantId);
    }

    @Override
    public List<SysUser> unallocatedList(SysUserVo user) {
        return userFeignClient.unallocatedList(user);
    }

    @Override
    public int deleteAuthUser(SysUserRole userRole) {
        Long[] userIds = {userRole.getUserId()};
        userRole.setUserIds(userIds);
        return userFeignClient.deleteAuthUser(userRole);
    }

    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
        SysUserRole sysUserRole = new SysUserRole();
        String tenantId = RequestContextUtil.getTenantId();
        sysUserRole.setUserIds(userIds);
        sysUserRole.setRoleId(roleId);
        sysUserRole.setTenantId(Long.valueOf(tenantId));
        return userFeignClient.deleteAuthUser(sysUserRole);
    }


    public void insertUserRole(Long userId, Long[] roleIds,String tenantId) {
        if (roleIds != null && roleIds.length > 0)
        {
            // 新增用户与角色管理
            List<SysUserRoleVo> list = new ArrayList<SysUserRoleVo>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRoleVo ur = new SysUserRoleVo();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                ur.setTenantId(tenantId);
                list.add(ur);
            }
            userFeignClient.addUserRole(list);
        }
    }
}
